package com.flow.asyncflow.core.node;


import com.flow.asyncflow.core.annotation.DataType;
import com.flow.asyncflow.core.annotation.NodeInfo;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@NodeInfo(name = "公共数据赋值")
public class PubGetData {

    public void SetPubData(Object baseObject, Object subObject, String subObjectName, Map<String, Object> keyValuePairs) throws IllegalAccessException, NoSuchFieldException {
        if (subObject == null) {
            return;
        }
        boolean isFirstPropertyInfo = false;
        if (baseObject == null) {
            isFirstPropertyInfo = true;

        }
        Class<?> clazz = subObject.getClass();
        int orderFlowPubGetDataType = 0;
        Annotation[] logMethods = clazz.getAnnotations();
        for (Annotation annotation : logMethods) {
            //获取方法名
            if (annotation instanceof DataType) {
                orderFlowPubGetDataType = ((DataType) annotation).asyncFlowPubDataType();
                break;
            }
        }

        if (isFirstPropertyInfo || orderFlowPubGetDataType == 1) {
            List<Field[]> fieldsList = new ArrayList<>();  // 保存属性对象数组到列表
            //获取实体类的所有属性，返回Field数组
            Field[] field = clazz.getDeclaredFields();
            fieldsList.add(field);
            Class<?> clazzsup = clazz.getSuperclass();
            while (clazzsup != null) {
                Field[] declaredFields = clazzsup.getDeclaredFields();  // 获取字节码对象的属性对象数组
                fieldsList.add(declaredFields);
                clazzsup = clazzsup.getSuperclass();
            }
            for (Object fields : fieldsList) {
                Field[] f = (Field[]) fields;
                // 获取属性的名字
                for (Field value : f) {
                    String name = value.getName(); // 获取属性的名字
                    value.setAccessible(true);
                    Object nestsObj = value.get(subObject);
                    SetPubData(subObject, nestsObj, name, keyValuePairs);

                }
            }

        } else {//if (orderFlowPubGetDataType == 2) {
            Class baseClazz = baseObject.getClass(); // 获取上一个层级类文件
            //当前对象在上一个类层级中的属性名
            if (keyValuePairs.get(subObjectName) != null) {
                Field f = baseClazz.getDeclaredField(subObjectName); // 获取该类的成员变量
                f.setAccessible(true);  // 取消语言访问检查

                f.set(baseObject, keyValuePairs.get(subObjectName));   // 给变量赋值


            }
        }
    }
}
